package com.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.Chapter;
import com.edu.entity.Video;
import com.edu.entity.chapter.ChapterVo;
import com.edu.entity.chapter.VideoVo;
import com.edu.exceptionhandler.MyException;
import com.edu.mapper.ChapterMapper;
import com.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-06-17
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

	@Autowired
	private VideoService videoService;

	@Override
	public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
		//1 根据课程id查询课程里面所有的章节
		QueryWrapper<Chapter> wrapperChapter = new QueryWrapper<>();
		wrapperChapter.eq("course_id",courseId);
		List<Chapter> chapterList = baseMapper.selectList(wrapperChapter);

		//2 根据课程id查询课程里面所有的小节
		QueryWrapper<Video> wrapperVideo = new QueryWrapper<>();
		wrapperChapter.eq("courseId",courseId);
		List<Video> videoList = videoService.list(wrapperVideo);

		//创建list集合，用于最终封装数据
		List <ChapterVo> finalList = new ArrayList<>();

		//3 遍历查询章节list	集合进行封装
		for (int i = 0; i < chapterList.size(); i++) {
			Chapter chapter = chapterList.get(i);
			ChapterVo chapterVo = new ChapterVo();
			BeanUtils.copyProperties(chapter,chapterVo);

			finalList.add(chapterVo);

			//用户封装小节
			ArrayList<VideoVo> videoVos = new ArrayList<>();

			for(int m = 0; m < videoList.size();m++){
				Video video = videoList.get(m);
				VideoVo videoVo = new VideoVo();
				if (video.getChapterId().equals(chapter.getId())){

					BeanUtils.copyProperties(video,videoVo);
					videoVos.add(videoVo);
				}
			}

			chapterVo.setChildren(videoVos);
		}
		//4 遍历查询小节list	集合进行封装

		return finalList;


	}

	@Override
	public boolean deleteChapter(String chapterId) {
		//根据chapterID 查询小节表，如果有数据，不删
		QueryWrapper<Video> wrapper = new QueryWrapper<>();
		wrapper.eq("chapter_id",chapterId);
		int count = videoService.count(wrapper);
		if (count>0){
			throw new MyException(20001,"不能删除");
		}else {
			//删除章节
			int result = baseMapper.deleteById(chapterId);
			return result > 0;
		}
	}

	@Override
	public void removeChapterByCourseId(String courseId) {
		QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
		wrapper.eq("course_id",courseId);
		baseMapper.delete(wrapper);
	}
}
